package com.da.javatest.interview.other.cglib2;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;

/**
 * @author chenlida
 * @date 2020/6/4 20:17
 * @description
 */
public class CglibTest2 implements IService1, IService2 {
    @Override
    public String m1() {
        return "method m1";
    }

    @Override
    public String m2() {
        return "method m2";
    }

    public static void main(String[] args) {
        Enhancer enhancer = new Enhancer();
        // 设置代理对象需要实现的接口
        enhancer.setInterfaces(new Class[] {IService1.class, IService2.class});
        // 通过Callback来对被代理方法进行增强
        enhancer.setCallback((MethodInterceptor)(o, method, objects, methodProxy) -> {
            System.out.println("方法：" + method.getName());
            return "Proxy";
        });

        // 这里只能代理接口，不能转成实现类CglibTest2
        IService1 proxy1 = (IService1)enhancer.create();
        System.out.println(proxy1.m1());

        IService2 proxy2 = (IService2)enhancer.create();
        System.out.println(proxy2.m2());
    }
}
